<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        let p1  = new Promise((resolve,reject)=>{
            setTimeout(() => {
                resolve(111)
            }, 1000);
        })

        let p2  = new Promise((resolve,reject)=>{
            setTimeout(() => {
                resolve(222)
                // reject("error");
            }, 100);
        })

        let p3  = new Promise((resolve,reject)=>{
            setTimeout(() => {
                resolve(333)
            }, 50);
        })


        // ---------------原有静态方法-------------------------------------------------------
        // Promise.allSettled()  可以执行多个promise对象 可以获取promise对象的fulfilled或rejected状态的结果  并带有一个对象数组，每个对象表示对应的 promise 结果。
        // 返回值:  每个promise对象的执行结果 存放在一个数组中 
        Promise.allSettled([p1,p2,p3]).then(res=>{
            console.log(res);
        })
        /* 
            [{status:"fulfilled",value:111},{status:"rejected"},reson:111]
        
        */

        // ---------------重写底层----------------------------------------------------------
        function MyallSettled(arr){
            return new Promise(reslove=>{
                // 创建一个数组 保存promise对象
                let resArr = new Array(arr.length);
                // 计数
                let count = 0;
                arr.forEach((p,key)=>{
                    p.then(res=>{
                        let obj = {
                            status : "fulfilled",
                            value : res
                        };
                        resArr[key] = obj;
                        count++;
                        if(count===arr.length){
                            reslove(resArr)
                        }
                    },err=>{
                        let obj = {
                            status:"rejected",
                            reson:err
                        };
                        resArr[key] = obj;
                        count++;
                        if(count===arr.length){
                            reslove(resArr)
                        }
                    })
                })
            })
        }

        MyallSettled([p1,p2,p3]).then(res=>{
            console.log(res);
        })


    </script>
</body>
</html>